package util

import (
	"errors"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

func ParseFileName(rawUrl string) (string, error) {
	fileUrl, err := url.Parse(rawUrl)
	if err != nil {
		return "", err
	}
	segs := strings.Split(fileUrl.Path, "/")
	return segs[len(segs)-1], nil

}

func DownloadFile(URL string) ([]byte, string, error) {
	fileName, err := ParseFileName(URL)
	if err != nil {
		return nil, "", err
	}
	resp, err := http.Get(URL)
	if err != nil {
		return nil, "", err
	}
	if resp == nil {
		return nil, "", errors.New("no response")
	}
	defer func() {
		_ = resp.Body.Close()
	}()
	body, err := ioutil.ReadAll(resp.Body)
	return body, fileName, err
}
